<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="读书笔记,《JavaScript 高级程序设计》,">





  <link rel="alternate" href="/atom.xml" title="卷柏的花期" type="application/atom+xml">






<meta name="description" content="本篇的重点在于了解两种函数的创建方式以及声明的先后差别，要熟练掌握 Function 类型外部的属性和方法以及内部的对象，最后大致理解 JS 程序的执行流程和原理。">
<meta name="keywords" content="读书笔记,《JavaScript 高级程序设计》">
<meta property="og:type" content="article">
<meta property="og:title" content="《JavaScript 高级程序设计》第五章：Function">
<meta property="og:url" content="http://yoursite.com/2019/04/02/professional-javascript-chapter-5-Function/index.html">
<meta property="og:site_name" content="卷柏的花期">
<meta property="og:description" content="本篇的重点在于了解两种函数的创建方式以及声明的先后差别，要熟练掌握 Function 类型外部的属性和方法以及内部的对象，最后大致理解 JS 程序的执行流程和原理。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://yoursite.com/2019/04/02/professional-javascript-chapter-5-Function/javascript.jpg">
<meta property="og:updated_time" content="2019-05-12T10:08:49.050Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="《JavaScript 高级程序设计》第五章：Function">
<meta name="twitter:description" content="本篇的重点在于了解两种函数的创建方式以及声明的先后差别，要熟练掌握 Function 类型外部的属性和方法以及内部的对象，最后大致理解 JS 程序的执行流程和原理。">
<meta name="twitter:image" content="http://yoursite.com/2019/04/02/professional-javascript-chapter-5-Function/javascript.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/04/02/professional-javascript-chapter-5-Function/">





  <title>《JavaScript 高级程序设计》第五章：Function | 卷柏的花期</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband">
    <a href="https://gitee.com/Selaginella/" target="_blank" style="position:absolute;right:0;top:0;border:none"><img src="https://gitee.com/Selaginella/Selaginella/widgets/widget_1.svg" alt="Fork me on Gitee"></a>
    </div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">卷柏的花期</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">随风而动，九死还生</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-source">
          <a href="/source/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-flask"></i> <br>
            
            资源
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/04/02/professional-javascript-chapter-5-Function/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Selaginella">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="卷柏的花期">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">《JavaScript 高级程序设计》第五章：Function</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-04-02T07:06:02+08:00">
                2019-04-01
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote class="blockquote-center"><img src="/2019/04/02/professional-javascript-chapter-5-Function/javascript.jpg" alt="&#39;JavaScript 高级程序设计&#39;">本篇的重点在于了解两种函数的创建方式以及声明的先后差别，要熟练掌握 <code>Function</code> 类型外部的属性和方法以及内部的对象，最后大致理解 JS 程序的执行流程和原理。</blockquote>

<a id="more"></a>
<h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><p>函数也是对象，每个函数都是 <code>Function</code> 类型的实例，只是函数的书写格式与普通对象的格式存在着很大的区别。<br>函数是对象，所以函数也具有属性和方法，例如：<code>length</code>、<code>prototype</code>、<code>bind</code>、<code>call</code>、<code>apply</code>等。<br>函数的类型有两种：“声明式函数”与“表达式函数”。函数名只是一个变量“标识符”而已，其保存的是对函数引用的指针，并非函数本身。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;;</span><br><span class="line"><span class="keyword">var</span> b = a;</span><br><span class="line"></span><br><span class="line">a= <span class="literal">null</span>;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">typeof</span> a <span class="comment">//null;</span></span><br><span class="line"><span class="keyword">typeof</span> b <span class="comment">//function</span></span><br></pre></td></tr></table></figure>
<p>证明一个函数就是对象的最简单的办法就是打印一个函数的详细内容：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">define</span>(<span class="params"></span>) </span>&#123; &#125;</span><br><span class="line"><span class="built_in">console</span>.dir(define);</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">    arguments: null</span></span><br><span class="line"><span class="comment">    caller: null</span></span><br><span class="line"><span class="comment">    length: 0</span></span><br><span class="line"><span class="comment">    name: "define"</span></span><br><span class="line"><span class="comment">    prototype: &#123;constructor: ƒ&#125;</span></span><br><span class="line"><span class="comment">    __proto__: ƒ ()</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>
<p>从实例代码中，我们可以发现创建的 <code>define</code> 函数也具有 <code>__proto__</code> 原型链属性和 <code>prototype</code> 原型属性。</p>
<h2 id="作为值的函数"><a href="#作为值的函数" class="headerlink" title="作为值的函数"></a>作为值的函数</h2><p>函数名也是“标识符”，其性质类似于变量，存储的是对函数引用的指针。<br>当函数名没有结合一对圆括号<code>()</code> 进行调用使用时，函数“指针”就可以作为值的形式通过函数名来进行赋值与传递。<br>示例中 <code>HOF</code> 类似于一个高阶函数，接收一个函数作为参数，并返回一个新的函数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">HOF</span>(<span class="params">fun</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> params = &#123;</span><br><span class="line">        key: <span class="string">'HOF'</span></span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="keyword">return</span> fun.bind(params);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> say = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; alert(<span class="string">'my is '</span> + <span class="keyword">this</span>.key); &#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> result = HOF(say);</span><br><span class="line"></span><br><span class="line">result(); <span class="comment">//my is HOF</span></span><br></pre></td></tr></table></figure>
<p>“作为值的函数” 另一种广泛使用的场景便是回调函数了，例如定义一个比较函数作为值来传入到 <code>sort</code> 方法中。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> data = [</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">"Zachary"</span>, <span class="attr">age</span>: <span class="number">28</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">"Nicholas"</span>, <span class="attr">age</span>: <span class="number">22</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">"Kims"</span>, <span class="attr">age</span>: <span class="number">21</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">"Time"</span>, <span class="attr">age</span>: <span class="number">20</span> &#125;,</span><br><span class="line">];</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createCompareFunction</span>(<span class="params">fieldName</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">first, second</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (first[fieldName] &lt; second[fieldName]) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (first[fieldName] &gt; second[fieldName]) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line">data.sort(createCompareFunction(<span class="string">"name"</span>)); <span class="comment">//按照名称升序。</span></span><br><span class="line">data.sort(createCompareFunction(<span class="string">"age"</span>)); <span class="comment">//按照年龄升序。</span></span><br></pre></td></tr></table></figure>
<h2 id="函数的声明提升"><a href="#函数的声明提升" class="headerlink" title="函数的声明提升"></a>函数的声明提升</h2><p>函数与变量一样存在着声明提升。<br>只有“声明式函数”存在着函数声明提升（function declaration hoisting）的特性。“函数表达式”则不存在这种情况。究其原因还是因为“函数表达式”符合变量声明与变量赋值的范畴。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">sum(<span class="number">1</span>, <span class="number">2</span>);  <span class="comment">//3</span></span><br><span class="line">reduce(<span class="number">2</span>,<span class="number">1</span>) <span class="comment">//Uncaught TypeError: reduce is not a function</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + b;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> reduce = <span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>) </span>&#123; <span class="keyword">return</span> a - b; &#125;</span><br></pre></td></tr></table></figure>
<p>当解析器向执行环境加载代码数据时，JavaScript 引擎会将需要声明的代码放在其它源代码树的顶部，在执行代码之前进行声明操作。也就是说，函数声明要早于普通代码的执行，上面的示例代码，实际情况如下所示：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//setp1:声明函数</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + b;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//step2:声明变量</span></span><br><span class="line"><span class="keyword">var</span> reduce = ;</span><br><span class="line"></span><br><span class="line"><span class="comment">//step3 执行函数</span></span><br><span class="line">sum(<span class="number">1</span>, <span class="number">2</span>) <span class="comment">//3</span></span><br><span class="line">reduce(<span class="number">2</span>, <span class="number">1</span>) <span class="comment">//Uncaught TypeError: reduce is not a function</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//step4 变量赋值</span></span><br><span class="line"></span><br><span class="line">reduce = <span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>) </span>&#123; <span class="keyword">return</span> a - b; &#125;</span><br></pre></td></tr></table></figure>
<h2 id="函数内部的对象"><a href="#函数内部的对象" class="headerlink" title="函数内部的对象"></a>函数内部的对象</h2><p>函数的内部有两个非常重要的对象：<code>this</code> 与 <code>arguments</code>。<br><code>this</code> 指向的是函数或方法的调用对象，当函数在全局环境中被执行时 <code>this</code> 一般指向的是 <code>window</code> 对象，而当函数作为某个对象的方法被调用时，则 <code>this</code> 指向的就是这个对象本身。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;<span class="keyword">this</span><span class="comment">//window&#125;</span></span><br><span class="line"><span class="keyword">var</span> b = &#123;</span><br><span class="line">    a:<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123; <span class="keyword">this</span> <span class="comment">//&lt;Object,b&gt;&#125;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>总结下：函数中的 <code>this</code> 通常指向的是 <code>window</code>，而作为方法中的 <code>this</code> 指向的则是这个方法所依附的对象本身。</p>
</blockquote>
<p>在严格模式 <code>use strict</code> 下，函数内部的 <code>this</code> 将不会指向 <code>window</code>，而是 <code>null</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">'use strict'</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">a</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">this</span>; <span class="comment">//undefined</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>全局作用域中的 this 在严格模式下指向的是 null，在非严格模式下指向的是window</li>
<li>当函数在全局环境中被执行时 <code>this</code> 一般指向的是 <code>window</code> 对象，在严格模式下同样是 null</li>
<li>方法中的 this 指向的是调用这个方法的对象本身</li>
<li>[ES6]箭头函数中的 this 指向的是上个作用域中的 this。</li>
</ul>
<p>关于 <code>arguments</code> 在第三章已经有过较为详细的说明，它是一个 <code>Like Array</code> 形式的对象。保存的是当前函数或方法的参数，其本身有一个 <code>length</code> 属性可以获取当前函数或方法的形参数量，除此之外，还有一个 <code>callee</code> 属性，返回对拥有这个 <code>arguments</code> 对象的函数自身的引用，通过 <code>callee</code> 属性我们可以运用“递归”方式，来实现一个阶乘的示例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">factory</span>(<span class="params">num</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(num &lt;=<span class="number">1</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> num * <span class="built_in">arguments</span>.callee(num<span class="number">-1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在某些需要引用自身的使用场景中 <code>callee</code> 属性可以非常好的减少代码的耦合度，另外 <code>callee</code> 属性自身还拥有一个<code>caller</code> 属性。<br>当拥有 <code>arguments</code> 对象的函数存在着被嵌套调用的情况。<code>caller</code> 属性的返回值就是这个函数的父函数的引用。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">b</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">arguments</span>.callee  <span class="comment">//ƒ b()&#123; arguments.callee; arguments.callee.caller;&#125;</span></span><br><span class="line">    <span class="built_in">arguments</span>.callee.caller;<span class="comment">//ƒ a()&#123; b();&#125;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">a</span>(<span class="params"></span>)</span>&#123; b();&#125;</span><br><span class="line"></span><br><span class="line">a();</span><br></pre></td></tr></table></figure>
<p>既然函数内部的 <code>arguments.callee</code> 返回的是函数自身，那么实际上函数本身也可以调用 <code>caller</code> 属性，即：<code>b.calleer</code>。<br>为了安全起见，ECMAScript 规定 <code>caller</code> 只有在被嵌套的函数上才会生效，普通的调用只会返回　<code>null</code>。<br>这样的设定也是为了防止同一环境中第三方代码对我们源码的窥探。<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">a</span>(<span class="params"></span>)</span>&#123;&#125;</span><br><span class="line">a.caller <span class="comment">// null</span></span><br></pre></td></tr></table></figure></p>
<blockquote>
<p>ES5 严格模式下 <code>arguments.callee</code> 属性会被拒绝访问，并且抛出 <code>TypeError</code> 的类型错误。</p>
</blockquote>
<h2 id="函数的属性与方法"><a href="#函数的属性与方法" class="headerlink" title="函数的属性与方法"></a>函数的属性与方法</h2><p><strong>length</strong> </p>
<p>length 返回函数当前的形参个数，其功能与 <code>arguments.length</code> 相同。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">function a()&#123;&#125;</span><br><span class="line">function b(a)&#123;&#125;</span><br><span class="line">function c(a,b)&#123;&#125;</span><br><span class="line"></span><br><span class="line">a.length //0</span><br><span class="line">b.length //1</span><br><span class="line">c.length 2</span><br></pre></td></tr></table></figure>
<p><strong>prototype</strong><br><code>prototype</code> 对象上定义的属性与方法都是用与被其实例对象(new 运算符)所继承，因此普通函数也可以充当构造器函数使用。</p>
 <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">a</span>(<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line">a.prototype.sayHello = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; alert(<span class="string">'hello'</span>) &#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> b = <span class="keyword">new</span> a();</span><br><span class="line">b.sayHello();</span><br></pre></td></tr></table></figure>
<blockquote>
<p>就如之前我们常说的 ECMAScript 中的很多引用类型都重写了自身的 <code>toString</code>、<code>toLocaleString</code>、<code>valueOf</code> 等方法一样，这些引用类型虽然通过原型链(<strong>proto</strong>) 继承了 Object上的 <code>toString</code>、<code>toLocaleString</code>、<code>valueOf</code> 方法，但是为了自身的特殊情况考量，也对自己的 prototype属性上进行了对应方法的重写，以让自己的实例对象继承调用。</p>
</blockquote>
<p><strong>caller</strong><br>当函数存在嵌套调用时，返回被嵌套函数父函数的引用。</p>
<p><strong>call() 与 apply()</strong></p>
<p>前面我们已经知道，作为函数并在全局环境中执行，this 默认指向的是 <code>window</code>。而在严格模式下则为 <code>null</code> 。如果作为方法，则 this 指向的是调用这个方法的对象本身。<br>函数对象自带的 <code>call</code> 与 <code>apply</code> 方法则可以自定义函数或方法内部的 this 指向。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> params = &#123; <span class="attr">color</span>: <span class="string">'Red'</span> &#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sayColor</span>(<span class="params">r, g, b</span>) </span>&#123;</span><br><span class="line">    alert(<span class="keyword">this</span>.color + <span class="string">':'</span> + r + <span class="string">','</span> + g + <span class="string">','</span> + b);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">say</span>(<span class="params">r, g, b</span>) </span>&#123;</span><br><span class="line">    sayColor.apply(params, <span class="built_in">arguments</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">sayColor.call(params, <span class="number">255</span>, <span class="number">255</span>, <span class="number">255</span>);</span><br><span class="line">say(<span class="number">255</span>, <span class="number">255</span>, <span class="number">255</span>);</span><br></pre></td></tr></table></figure>
<p>从示例中可以看出，<code>call</code> 与 <code>apply</code> 在功能上是相同的，主要区别是接收的参数形式不同，call 方法依次接收，而 apply 方法则可以接收一个参数数组。<br>因此在具体的使用中是选择 <code>call</code> 还是 <code>apply</code> 最主要的抉择还是调用时传参的形式。</p>
<p><strong>bind()</strong></p>
<p><code>bind</code> 方法是 ES5 标准新加入的方法，兼容性上 IE9+ 、FF4+、Safari 5.1+。<br><code>bind</code> 方法也可以改变一个函数或方法内部的 this 指向，在使用格式上也与 <code>call</code> 方法完全相同。<br><code>bind</code> 方法与 <code>call</code> 或者是 <code>apply</code> 等方法最大的区别就是 <code>bind</code> 方法在改变 this 指向后并不会立即调用函数而是返回一个新的函数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> params = &#123; <span class="attr">color</span>: <span class="string">'Red'</span> &#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">say</span>(<span class="params">r, g, b</span>) </span>&#123;</span><br><span class="line">    alert(<span class="keyword">this</span>.color + <span class="string">':'</span> + r + <span class="string">','</span> + g + <span class="string">','</span> + b);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> sayColor = say.bind(params, <span class="number">255</span>, <span class="number">255</span>, <span class="number">255</span>);</span><br><span class="line"></span><br><span class="line">sayColor();</span><br></pre></td></tr></table></figure>
<blockquote>
<p><code>call</code> 、<code>apply</code> 、 <code>bind</code> 等方法的第一个参数就是函数或方法内部 this 所要指向的对象。其它的参数与普通函数或方法的形参相同。</p>
</blockquote>
<h2 id="函数的转换方法"><a href="#函数的转换方法" class="headerlink" title="函数的转换方法"></a>函数的转换方法</h2><p><code>Function</code> 类型也在自己的 <code>prototype</code> 上重写了适合自身的 <code>toString</code>、<code>toLocaleString</code>、<code>valueOf</code>等方法。<br><code>toString</code>、<code>toLocaleString</code>　在不同的浏览器，不同的平台其返回值不尽相同。而 <code>valueOf</code> 则通常返回函数实例对象自身。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">a</span>(<span class="params"></span>)</span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">a.toString() <span class="comment">//"function a()&#123;&#125;"</span></span><br><span class="line">a.toLocaleString() <span class="comment">//"function a()&#123;&#125;"</span></span><br><span class="line">a.valueOf() <span class="comment">//ƒ a()&#123;&#125;</span></span><br></pre></td></tr></table></figure>
<h2 id="代码执行原理"><a href="#代码执行原理" class="headerlink" title="代码执行原理"></a>代码执行原理</h2><p>在简单学过“执行上下文”，“作用域”、“作用域链”、“变量提升”、“函数（arguments\this）”等基础知识后，现在我们尝试把这些零碎的知识点串联起来，去整体的理解和学习。</p>
<p>JavaScript 中可执行的代码(Execution Code)分为三种：“全局代码”、“函数代码”，“Eval代码”。</p>
<ul>
<li>全局代码：全局作用域下的 JS 代码，通常可以理解为附加在 <code>window</code> 对象上的代码。</li>
<li>函数代码：函数中的代码，具有封闭独立的局部作用域。</li>
<li>Eval代码：ES5 已不建议使用。</li>
</ul>
<p>JS 引擎在执行这些代码时会首先创建对应类型的执行上下文（Execution Context，EC）即：“全局执行上下文”、“函数执行上下文”。每个执行上下文都可以抽象理解为具有较为封闭的空间或容器，因此在一个 JS 程序中必然有且只有一个的执行上下文便是“全局执行上下文”，而其它的大多数都是“函数执行上下文”。</p>
<p>在 JS 中用来管理“执行上下文”的是 – “执行上下文栈(Execution context stack，ECS)”。“执行上下文栈”类似于 <code>Array</code> 类型中的“栈”结构。每当 JavaScript 引擎在创建一个执行上下文时，便会将其依次 <code>push</code> 到执行栈中，而作为最早创建的执行上下文 - “全局执行上下文”必然在“执行栈”的最底部。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> ECStack = [];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 首先加载“全局执行上下文”</span></span><br><span class="line"></span><br><span class="line">ECStack.push(<span class="string">'&lt;globalContext&gt;'</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 随着代码的执行，其它的执行上下文也会被依次加入到这个 执行栈中。</span></span><br><span class="line"></span><br><span class="line">ECStack.push(<span class="string">'&lt;fun1&gt;,functionContext'</span>);</span><br><span class="line">ECStack.push(<span class="string">'&lt;fun2&gt;,functionContext'</span>);</span><br><span class="line">ECStack.push(<span class="string">'&lt;fun3&gt;,functionContext'</span>);</span><br></pre></td></tr></table></figure>
<p>理解了“执行栈”与“执行上下文”的关系后，我们可以想象出 JS 程序的执行，就像是在一条流水线上源源不断的将包装盒传送到对应的机器中进行拆解处理，每个包装盒的拆解都类似于一个“执行上下文”的执行。当“执行栈”中的某个执行上下文执行完毕后，便会将其从“执行栈”中弹出，其内部的代码、资源、标识符也统统会被销毁。所以 JavaScript 代码不仅仅是一行一行的顺序执行，更严格的来说是一块一块（执行上下文）的顺序执行。</p>
<p>如上所述“执行上下文”我们可以将其抽象理解成一个包装盒，每个包装盒的内部都存放着三个非常重要的物品（对象）：</p>
<ul>
<li>变量对象(VO)/活动对象(AO)</li>
<li>this对象</li>
<li>作用域链(scope chain)</li>
</ul>
<p>当 JS 引擎进入到执行上下文的内部并开始执行代码时，会首先向该上下文中加载代码与所需的数据，然后将需要声明的函数与变量放在源代码树的顶部，进行预先声明，声明后的变量与函数会被加入到“变量对象(VO)” 中进行管理。<br>“变量对象(VO)” 的结构是一个 <code>Map</code> 结构。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">1</span>;</span><br><span class="line"><span class="keyword">var</span> b = <span class="number">2</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">c</span>(<span class="params"></span>)</span>&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//---------------------------</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> EC_GlobalContext = &#123;</span><br><span class="line">    VO:&#123;</span><br><span class="line">        a:<span class="number">1</span>,</span><br><span class="line">        b:<span class="number">2</span>,</span><br><span class="line">        c:<span class="string">'reference to function c()&#123;&#125;'</span>,</span><br><span class="line">        alert:<span class="string">'ƒ alert() &#123; [native code] &#125;'</span>,</span><br><span class="line">        ...</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="keyword">this</span>:<span class="string">'reference to window'</span>,</span><br><span class="line">    scopeChain:<span class="literal">null</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//---------------------------</span></span><br></pre></td></tr></table></figure>
<p>在全局执行上下文中，我们可以认为“变量对象(VO)” 就是 <code>window</code> 对象，也就是说在“全局上下文”中变量对象是可访问，可赋值的 。但在“函数执行上下文”中，“变量对象(VO)” 将无法被直接访问，而且在“函数执行上下文”中变量对象相比“全局执行上下文”又增加了 <code>arguments</code> 对象，此时的变量对象也被称之为“活动对象(AO)”。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> AO = &#123;</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">    <span class="built_in">arguments</span>:&#123;</span><br><span class="line">        <span class="number">0</span>:<span class="string">'[value1]'</span>,</span><br><span class="line">        <span class="number">1</span>:<span class="string">'[value2]'</span>,</span><br><span class="line">        <span class="comment">//....,</span></span><br><span class="line">        length:<span class="string">'[number]'</span>,</span><br><span class="line">        callee:<span class="string">'&lt;function,self&gt;'</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">//....</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>每个“执行上下文”都有属于自己的独立空间，因此具有关联的多个执行上下文，会通过“作用域链(scope chain)”来进行关联，每个执行上下文内的的标识符解析都会率先从自身的“变量对象”中查找，如果查找不到，则沿着作用域链的关联路径继续向上解析，一直到达“全局执行上下文”，因此我们所说的容器与封闭空间的概念，实际上就是我们常说的 —— “作用域”。</p>
<blockquote>
<p>或者说作用域的范围实则是作用域链的最大延伸范围。</p>
</blockquote>
<p>在执行上下文中，作用域链的关联关系是通过多个“执行上下文”是否存在嵌套关系来确定的，例如在 JS 中所有局部代码都嵌套在全局代码中，因此所有局部执行上下的作用域链的最顶层都会是“全局执行上下文”，这也说明为什么我们不论在哪里书写局部代码，总可以访问到 <code>window</code> 对象上的方法或属性。为什么是嵌套而不是其它呢？原因是 JS 这门语言属于词法作用域（lexcial scope） 而非动态作用域(Dynamic scope)，其作用域的访问只在乎代码在哪里书写，而非在哪里执行。<br>看下面的代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fn1</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> chain2 = <span class="string">'lexical'</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">fn3</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(chain2);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    fn3();</span><br><span class="line"></span><br><span class="line">    <span class="built_in">console</span>.log(chain1)</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fn2</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> chain1 = <span class="string">'dynamic'</span>;</span><br><span class="line">    fn1();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"> fn2();</span><br></pre></td></tr></table></figure>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wx.jpg" alt="Selaginella 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Selaginella 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/读书笔记/" rel="tag"># 读书笔记</a>
          
            <a href="/tags/《JavaScript-高级程序设计》/" rel="tag"># 《JavaScript 高级程序设计》</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/04/01/professional-javascript-chapter-5-Array/" rel="next" title="《JavaScript 高级程序设计》第五章：Array">
                <i class="fa fa-chevron-left"></i> 《JavaScript 高级程序设计》第五章：Array
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/04/11/professional-javascript-chapter-5-RegExp/" rel="prev" title="《JavaScript 高级程序设计》第五章：RegExp">
                《JavaScript 高级程序设计》第五章：RegExp <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTkxNC8xODQ2MA"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/uploads/avatar.jpg" alt="Selaginella">
            
              <p class="site-author-name" itemprop="name">Selaginella</p>
              <p class="site-description motion-element" itemprop="description">知识在于积累，努力必有收获</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/shenguotao2015" target="_blank" title="gitHub">
                      
                        <i class="fa fa-fw fa-github"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/Selaginella" target="_blank" title="码云">
                      
                        <i class="fa fa-fw fa-telegram"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://www.cnblogs.com/HCJJ/" target="_blank" title="博客园">
                      
                        <i class="fa fa-fw fa-rss-square"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:sgt_ah@163.com" target="_blank" title="Email">
                      
                        <i class="fa fa-fw fa-envelope"></i></a>
                  </span>
                
            </div>
          

          
          

          
          

          
        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#简介"><span class="nav-number">1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#作为值的函数"><span class="nav-number">2.</span> <span class="nav-text">作为值的函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#函数的声明提升"><span class="nav-number">3.</span> <span class="nav-text">函数的声明提升</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#函数内部的对象"><span class="nav-number">4.</span> <span class="nav-text">函数内部的对象</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#函数的属性与方法"><span class="nav-number">5.</span> <span class="nav-text">函数的属性与方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#函数的转换方法"><span class="nav-number">6.</span> <span class="nav-text">函数的转换方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#代码执行原理"><span class="nav-number">7.</span> <span class="nav-text">代码执行原理</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-snowflake-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Selaginella<span class="with-love"><i class="fa fa-heart"></i></span>Hexo 强力驱动</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>




















  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
